import React from 'react';
import contractService from 'containers/approve/contract/contract.service';
import { Form, Button, Input, Row, Col, Select, InputNumber, DatePicker, message } from 'antd';
import moment from 'moment';
import { messages } from 'share/common';
import Chooser from 'components/chooser';
import { connect } from 'react-redux';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

class NewPayPlan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      headerData: {},
      record: props.params.payInfo || {},
      searcherLov: {
        disabled: true
      },
      contractCategoryValue: '',
      partnerCategoryOptions: [], //合同方类型选项
      venderOptions: [], //供应商选项,
      companyId: '',
      partnerId: '',
      partnerName: '',
      show: false
    };
  }

  componentWillMount() {
    this.getSystemValueList(2107)
      .then(res => { //合同方类型
        let partnerCategoryOptions = res.data.values || [];
        this.setState({ partnerCategoryOptions });
      });
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.params.flag && nextProps.params.flag) {
      this.setState({
        headerData: nextProps.params.contractHead,
        searcherLov: {
          disabled: !nextProps.params.contractHead.partnerCategory
        },
        record: nextProps.params.payInfo
      });
    }
    if (this.props.params.flag && !nextProps.params.flag) {
      this.props.form.resetFields();
    }
  }

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({ record: {} });
    this.props.close();
  };

  //保存
  handleSave = (e) => {
    e.preventDefault();
    const { record } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.headerId = this.state.headerData.id;
        values.dueDate = moment(values.dueDate)
          .format('YYYY-MM-DD');
        values.partnerId = record.partnerId;
        values.partnerName = record.partnerName;
        this.setState({ loading: true });
        contractService.newPayPlan(values)
          .then(res => {
            if (res.status === 200) {
              this.props.close(true);
              this.props.form.resetFields();
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.setState({ loading: false });
            }
          })
          .catch(e => {
            this.setState({ loading: false });
            message.error(`${messages('common.save.filed'/*保存失败*/)}, ${e.response.data.message}`);
          });
      }
    });
  };

  //更新
  handleUpdate = (e) => {
    e.preventDefault();
    const { record } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.id = record.id;
        values.headerId = record.headerId;
        values.versionNumber = record.versionNumber;
        values.dueDate = moment(values.dueDate)
          .format('YYYY-MM-DD');
        values.partnerId = record.partnerId;
        values.partnerName = record.partnerName;
        this.setState({ loading: true });
        contractService.updatePayPlan(values)
          .then(res => {
            if (res.status === 200) {
              this.props.form.resetFields();
              this.props.close(true);
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.setState({ loading: false, record: {} });
            }
          })
          .catch(e => {
            this.setState({ loading: false });
            if (e.response) {
              message.error(`${messages('common.save.filed'/*保存失败*/)}, ${e.response.data.message}`);
            }
          });
      }
    });
  };


  changePartnerCategory = (value) => {
    let { record } = this.state;
    record.partnerCategory = value;
    this.setState({ record });
    this.props.form.setFieldsValue({ partnerId: undefined });
  };

  checkPrice = (rule, value, callback) => {
    if (value > 0) {
      callback();
      return;
    }
    callback(messages('my.contract.amount.tips'));
  };

  //四舍五入 保留两位小数
  toDecimal2 = (e) => {

    let x = e.target.value;
    let f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    f = Math.round(x * 100) / 100;
    let s = f.toString();
    let rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    this.props.form.setFieldsValue({ amount: s });
  };

  //渲染收款方
  renderPayeeId = () => {
    const { record } = this.state;
    const venderParams = {
      companyOid: this.props.company.companyOID
    };
    let payeeType = record.partnerCategory;
    return <Chooser type={payeeType === 'EMPLOYEE' ? 'bgtUser' : 'vendor_account'}
                    valueKey='id'
                    labelKey={payeeType === 'EMPLOYEE' ? 'fullName' : 'venNickname'}
                    method='get'
                    single={true}
                    itemMap
                    showClear={false}
                    placeholder={messages('common.please.select')}
                    onChange={this.selectUser}
                    listExtraParams={payeeType === 'EMPLOYEE' ? null : venderParams}/>;
  };

  selectUser = (value) => {
    let { record } = this.state;
    record.partnerId = value[0].id;
    record.partnerCategory === 'EMPLOYEE' ? record.partnerName = value[0].fullName : record.partnerName = value[0].venNickname;
    this.setState({ record });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, headerData, record, partnerCategoryOptions } = this.state;
    let autoPartnerId = [];
    switch (record.partnerCategory) {
      case 'EMPLOYEE':
        record.partnerId
          ? autoPartnerId.push({ id: record.partnerId, fullName: record.partnerName })
          : autoPartnerId = undefined;
        break;
      case 'VENDER':
        record.partnerId
          ? autoPartnerId.push({ id: record.partnerId, venNickname: record.partnerName })
          : autoPartnerId = undefined;
        break;
      default:
        autoPartnerId = undefined;
        break;
    }

    const formItemLayout = {
      labelCol: { span: 8, },
      wrapperCol: { span: 10 },
    };
    return (
      <div className="new-pay-plan" style={{ marginTop: 20 }}>
        <Form onSubmit={record.id ? this.handleUpdate : this.handleSave}>
          <Row>
            <Col span={8} className="ant-form-item-label label-style">{messages('budget.occupancy.amount'/*金额*/)}： </Col>
            <Col span={4}>
              <FormItem>
                {getFieldDecorator('currency', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select'/*请选择*/)
                  }],
                  initialValue: headerData.currency
                })(
                  <Input disabled/>
                )}
              </FormItem>
            </Col>
            <Col span={6} style={{ marginLeft: 3 }}>
              <FormItem className="ant-col-offset-1">
                {getFieldDecorator('amount', {
                  rules: [{ validator: this.checkPrice }],
                  initialValue: record.amount
                })(
                  <InputNumber precision={2} onBlur={this.toDecimal2}
                               placeholder={messages('common.please.enter'/*请输入*/)}
                               style={{ width: '99%' }}/>
                )}
              </FormItem>
            </Col>
          </Row>

          <FormItem {...formItemLayout} label={messages('my.contract.partner.type'/*合同方类型*/)}>
            {getFieldDecorator('partnerCategory', {
              rules: [{
                required: true,
                message: messages('common.please.select'/*请选择*/)
              }],
              initialValue: record.id ? record.partnerCategory : ''
            })(
              <Select
                placeholder={messages('common.please.select'/*请选择*/)}
                onChange={this.changePartnerCategory}
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {partnerCategoryOptions.map((option) => {
                  return <Option key={option.value}>{option.messageKey}</Option>;
                })}
              </Select>
            )}
          </FormItem>

          {this.props.params.flag &&
          <FormItem {...formItemLayout} label={messages('pay.refund.partnerName'/*收款方*/)}>
            {getFieldDecorator('partnerId', {
              rules: [{
                required: true,
                message: messages('common.please.enter'/*请输入*/) },
                {
                  validator: (item, value, callback) => {
                    if (!(value && value[0].id)) {
                      callback(messages('common.please.select'));
                    }
                    callback();
                  }
                }
              ], initialValue: autoPartnerId })
            (
              this.renderPayeeId()
            )}
          </FormItem>
          }

          <FormItem {...formItemLayout} label={messages('my.contract.plan.pay.date'/*计划付款日期*/)}>
            {getFieldDecorator('dueDate', {
              rules: [{
                required: true,
                message: messages('common.please.select'/*请选择*/)
              }],
              initialValue: record.id ? moment(record.dueDate) : null
            })(
              <DatePicker style={{ width: '100%' }}/>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('common.remark'/*备注*/)}>
            {getFieldDecorator('remark', {
              initialValue: record.remark
            })(
              <TextArea autosize={{ minRows: 2 }}
                        style={{ minWidth: '100%' }}
                        placeholder={messages('common.please.enter'/*请输入*/)}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit"
                    loading={loading}>{messages('common.save'/*保存*/)}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel'/*取消*/)}</Button>
          </div>
        </Form>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  };
}

const wrappedNewPayPlan = Form.create()((NewPayPlan));
export default connect(mapStateToProps)(wrappedNewPayPlan);
